﻿using AuthorityManagement.Model;
using AuthorityManagement.Model.Dto.TreeMenuDto;
using AutoMapper;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using NPOI.HPSF;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static AuthorityManagement.Helper.RuturnHelper;

namespace AuthorityManagement.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TreeMenuController :  ControllerBase
    {
        private readonly ISqlSugarClient _Db;
        private IMapper _mapper;
        public TreeMenuController(ISqlSugarClient db, IMapper mapper)
        {
            _Db = db;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取树形菜单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetTreeMenuId")]
        public async Task<dynamic> GetTreeMenuId(string id)
        {
            var data = await _Db.Queryable<TreeMenu>().Where(it => it.Id == id).FirstAsync();
            return data;
        }
        /// <summary>
        /// 新增树形菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<dynamic> Create([FromBody]TreeMenuCrInput input)
        {
            var data = input.Adapt<TreeMenu>();
            data.Id = Guid.NewGuid().ToString();
            data.CreateUser = "admin";
            data.CreateTime = DateTime.Now;
            var isOk = await _Db.Insertable(data).ExecuteCommandAsync();
            if (isOk < 0)
            {
                return RR.Success("新增失败！");
            }
            else
            {
                return RR.Success("新增成功！");
            }
        }

        /// <summary>
        /// 编辑树形菜单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("Update")]
        public async Task<dynamic>Update(string id, [FromBody] TreeMenuUpInput input)
        {
            var data = input.Adapt<TreeMenu>();
            var isOk = await _Db.Updateable(data).ExecuteCommandAsync();
            if (isOk < 0)
            {
                return RR.Success("编辑失败！");
            }
            else
            {
                return RR.Success("编辑成功！");
            }
        }
        /// <summary>
        /// 获取树形菜单列表
        /// </summary>
        /// <returns></returns>

        [HttpGet("GetMenuTreeAsync")]
        public async Task<List<TreeMenuDto>> GetMenuTreeAsync()
        {
            var treemenulist =await  _Db.Queryable<TreeMenu>().ToListAsync();
            List<TreeMenuDto> tree = new List<TreeMenuDto>();
            foreach (var item in treemenulist)
            {
                //tree.Add(_mapper.Map<TreeMenuDto>(item));
                tree.Add(item.Adapt<TreeMenuDto>());
            }
            var Treelist = GetMenuTree(tree, "-1");
            return Treelist;
        }

        /// <summary>
        /// 递归方法获取树形菜单
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        private static List<TreeMenuDto> GetMenuTree(List<TreeMenuDto> list, string pid)
        {
            List<TreeMenuDto> tree = new List<TreeMenuDto>();
            var children = list.Where(m => m.ParentId == pid).ToList();
            if (children.Count > 0)
            {
                for (var i = 0; i < children.Count; i++)
                {
                    TreeMenuDto itemMenu = new TreeMenuDto();
                    //itemMenu.item=children[i];
                    itemMenu.Id = children[i].Id;
                    itemMenu.Desc = children[i].Desc;
                    itemMenu.ParentId = children[i].ParentId;
                    itemMenu.Children = GetMenuTree(list, children[i].Id);
                    tree.Add(itemMenu);
                }
            }
            return tree;
        }
        /// <summary>
        /// 删除树形菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Delete")]
        public async Task<dynamic> Delete(string id)
        {
            var data = await _Db.Deleteable<TreeMenu>().Where(it => it.Id == id).ExecuteCommandAsync();
            if (data!>0)
            {
                return RR.Error("删除失败！");
            }
            else
            {
                return RR.Success("删除成功！");
            }
        }

        /// <summary>
        /// TreeMenuDto
        /// </summary>
        public class TreeMenuDto
        {
            /// <summary>
            /// id
            /// </summary>
            public string Id { get; set; }
            /// <summary>
            /// 父级id
            /// </summary>
            public string ParentId { get; set; }
            /// <summary>
            /// 描述
            /// </summary>
            public string Desc { get; set; }
            /// <summary>
            /// 子级集合
            /// </summary>

            public List<TreeMenuDto> Children { get; set; }=new List<TreeMenuDto>();
        }

        #region 树形下拉
        [HttpGet("GetMenuTreeSelectAsync")]
        public async Task<List<TreeMenuSelectDto>> GetMenuTreeSelectAsync()
        {
            var treemenulist = await _Db.Queryable<TreeMenu>().ToListAsync();
            List<TreeMenuSelectDto> tree = new List<TreeMenuSelectDto>();
            foreach (var item in treemenulist)
            {
                tree.Add(_mapper.Map<TreeMenuSelectDto>(item));
                //tree.Add(item.Adapt<TreeMenuSelectDto>());
            }
            var Treelist = GetMenuTreeSelect(tree, "-1");
            return Treelist;
        }

        private static List<TreeMenuSelectDto> GetMenuTreeSelect(List<TreeMenuSelectDto> list, string pid)
        {
            List<TreeMenuSelectDto> tree = new List<TreeMenuSelectDto>();
            var children = list.Where(m => m.ParentId == pid).ToList();
            if (children.Count > 0)
            {
                for (var i = 0; i < children.Count; i++)
                {
                    TreeMenuSelectDto itemMenu = new TreeMenuSelectDto();
                    //itemMenu.item=children[i];
                    itemMenu.Id = children[i].Id;
                    itemMenu.Name = children[i].Name;
                    itemMenu.ParentId = children[i].ParentId;
                    itemMenu.Children = GetMenuTreeSelect(list, children[i].Id);
                    tree.Add(itemMenu);
                }
            }
            return tree;
        }


        public class TreeMenuSelectDto
        {
            /// <summary>
            /// id
            /// </summary>
            public string Id { get; set; }
            /// <summary>
            /// 父级id
            /// </summary>
            public string ParentId { get; set; }
            /// <summary>
            /// 描述
            /// </summary>
            public string Name { get; set; }
            /// <summary>
            /// 子级集合
            /// </summary>

            public List<TreeMenuSelectDto> Children { get; set; } = new List<TreeMenuSelectDto>();
        }
        #endregion
    }
}
